import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:shenling_flutter/pages/task/index.dart';
import '../utils/eventbus.dart';
import '../utils/token.dart';
import 'message/index.dart';
import 'mine/index.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  @override
  void initState() {
    super.initState();
    // 先获取token
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });

    eventBus.on<LogoutEvent>().listen((event) {
      // 跳转登录页面
      Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
    });
  }

  // 记录当前索引
  int currentIndex = 0;

  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "任务",
      "img": "assets/tabs/ic_tab_btn_task.svg",
    },
    {
      "title": "消息",
      "img": "assets/tabs/ic_tab_btn_mess_nor.svg",
    },
    {
      "title": "我的",
      "img": "assets/tabs/ic_tab_btn_mine_nor.svg",
    }
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: IndexedStack(
          index: currentIndex,
          children: [
            TaskPage(),
            MessagePage(),
            MinePage(
              currentIndex: currentIndex,
            )
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: barItemList(),
        currentIndex: currentIndex,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
            icon: SvgPicture.asset(
              item['img'],
              color: Colors.grey,
              width: 24,
              height: 24,
            ),
            activeIcon: SvgPicture.asset(
              item['img'],
              color: Colors.red,
              width: 24,
              height: 24,
            ),
            label: item['title']),
      );
    }
    return items;
  }
}
